package com.xsz.pda.net.api

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.alibaba.fastjson.TypeReference
import com.blankj.utilcode.util.DeviceUtils
import com.github.kittinunf.fuel.httpDownload
import com.github.kittinunf.fuel.httpGet
import com.github.kittinunf.fuel.httpPost
import com.xsz.pda.api.beans.ApiResult
import com.xsz.pda.api.beans.TicketType
import com.xsz.pda.net.Constant.*
import java.io.File


private const val HTTP_TIMEOUT = 2000

class Api(val ip: String){
    private var baseUrl = "http://$ip:$CONTROL_SERVER_PORT"

    fun register(
        androidId: String,
        name: String,
        groupId: String,
        suc: (String?, String?, ticketTypes: List<String>?) -> Unit,
        fail: (String) -> Unit
    ) {
        "$baseUrl$CONTROL_URL_REGISTER"
            .httpPost(listOf("androidId" to androidId, "name" to name, "groupId" to groupId))
            .timeout(timeout = HTTP_TIMEOUT)
            .responseString { _, _, rlt ->
                rlt.fold(
                    {
                        val apiResult = JSON.parseObject<ApiResult<JSONObject>>(
                            it,
                            object : TypeReference<ApiResult<JSONObject>>() {}.type
                        )
                        if (apiResult.isSuccess) {
                            val json = apiResult.result
                            val typeArr = json.getJSONArray("ticketTypes")
                            var typeList:List<String> = ArrayList()
                            if (typeArr!=null && !typeArr.isEmpty()) {
                                typeList = typeArr.toJavaList(String::class.java)
                            }
                            suc(json.getString("projectId"), json.getString("projectNo"), typeList)
                        } else {
                            fail(apiResult.message)
                        }
                    },
                    { fail("无法连接服务器") })
            }
    }

    fun getTicketTypes(suc: (List<String>) -> Unit,
                       fail: (String) -> Unit) {
        "$baseUrl$CONTROL_URL_DEVICE_CONFIG/${DeviceUtils.getAndroidID()}"
            .httpGet()
            .timeout(timeout = HTTP_TIMEOUT)
            .responseString { _, _, rlt ->
                rlt.fold(
                    {
                        val apiResult =JSON.parseObject<ApiResult<List<TicketType>>>(it, object :TypeReference<ApiResult<List<TicketType>>>(){}.type)
                        if (apiResult.isSuccess) {
                            suc(apiResult.result.map { it.ticketTypeId })
                        } else {
                            fail(apiResult.message)
                        }
                    },
                    { fail("无法连接服务器") })
            }

    }

    fun downloadApk(versionId: String,
                    saveFile: File,
                    processCallback: (progress: Float)->Unit,
                    callback: (Boolean) -> Unit
    ) {
        "$baseUrl/version/$versionId/download"
            .httpDownload()
            .fileDestination { _, _ -> saveFile }
            .progress { readBytes, totalBytes ->
                val progress = readBytes.toFloat() / totalBytes.toFloat() * 100
                processCallback(progress)
            }
            .response {
                    result ->
                result.fold({ callback(true) },
                    { callback(false) })
            }
    }

}